<template>
  <template v-if="getShow">
    <LoginFormTitle class="enter-x" />
    <!-- <div class="gp mt-4 mb-2"> Tip：演示系统未开放扫码登录，请联系官方人员获取账号密码。 </div> -->
    <div class="enter-x min-h-64 min-w-64">
      <!-- <QrCode
        :value="qrCodeUrl"
        class="enter-x flex justify-center xl:justify-start"
        :width="280"
      /> -->
      <Image
        :src="pictureUrl"
        class="enter-x flex cursor-pointer justify-center xl:justify-start"
        :width="280"
        :preview="false"
        @click="qrcodeGen"
      />
      <Divider class="enter-x size">{{ t('请使用微信扫描二维码，点击图片刷新！') }}</Divider>
      <Button size="large" block class="enter-x mt-4" @click="handleBackLogin">
        {{ t('sys.login.backSignIn') }}
      </Button>
    </div>
  </template>
</template>
<script lang="ts" setup>
  import { computed, watch, ref, unref } from 'vue';
  import LoginFormTitle from './LoginFormTitle.vue';
  import { Button, Divider, Image } from 'ant-design-vue';
  // import { QrCode } from '/@/components/Qrcode/index';
  import { PageEnum } from '/@/enums/pageEnum';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useLoginState, LoginStateEnum } from './useLogin';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { publicPath } from '/@/utils/env';

  const { showMessage, showMessageModal } = useMessage();

  const blankImg =
    '';
  const apiPrefix = '/wx/qrcode/default';
  const pictureUrl = ref(blankImg);
  const sceneId = ref();
  const timer = ref();

  async function qrcodeGen() {
    qrcodeClear();
    const res = await defHttp.get({ url: apiPrefix + '/picture' });
    sceneId.value = res.sceneId;
    pictureUrl.value = res.pictureUrl;
    timer.value = setInterval(qrcodeLogin, 2000);
  }

  async function qrcodeLogin() {
    if (!sceneId.value) return;
    const res = await defHttp.get(
      { url: apiPrefix + '/login/' + sceneId.value },
      { errorMessageMode: 'none' },
    );
    if (res.result == 'true') {
      qrcodeClear();
      if (res.user) {
        showMessage(res.message);
        window.location.href = publicPath + PageEnum.BASE_HOME;
      } else {
        showMessageModal({ content: res.message });
        sceneId.value = null;
        pictureUrl.value = blankImg;
      }
    }
  }

  function qrcodeClear() {
    if (timer.value) {
      clearInterval(timer.value);
    }
  }

  const { t } = useI18n();
  const { handleBackLogin, getLoginState } = useLoginState();

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.QR_CODE);

  watch(getShow, (show) => {
    if (show) qrcodeGen();
  });
</script>
